package com.sxbbc.plat.controller.jz;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.function.common.GetRest;
import com.function.common.RestResponse;
import com.sxbbc.common.basics.exceptions.ThrowJsonException;
import com.sxbbc.common.basics.rest.RestFactory;
import com.sxbbc.common.basics.utils.calculation.CalcuUtils;
import com.sxbbc.common.basics.utils.statics.StaticUtils;
import com.sxbbc.common.core.dto.jz.AccountDetailVO;
import com.sxbbc.common.core.entity.jz.*;
import com.sxbbc.common.core.enums.AgentLevelEnums;
import com.sxbbc.common.core.enums.FundTypeEnums;
import com.sxbbc.common.core.enums.HandleTypeEnums;
import com.sxbbc.common.core.service.*;
import com.sxbbc.common.core.utils.BasePage;
import com.sxbbc.plat.common.AgentMapping;
import com.sxbbc.plat.util.SystemLog;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.*;

/**
 * 代理 控制层
 *
 * @author leehao
 * @date 2019-07-08
 */
@Controller
public class AgentController {

    @Autowired
    private IAgAgentService agAgentService;
    @Autowired
    private IAgRolesService agRolesService;
    @Autowired
    private IAgDonateDetailService agDonateDetailService;
    @Autowired
    private IAgMenusService agMenusService;
    @Autowired
    private IAgAccountService iAgAccountService;
    @Autowired
    private IAddressService addressService;
    @Autowired
    private IAccountChangeService accountChangeService;
    @Autowired
    private IAgMoneyDetailService iAgMoneyDetailService;
    @Autowired
    private IAgDonateDetailService iAgDonateDetailService;
    @Autowired
    private IAgShareDetailService iAgShareDetailService;

    /**
     * 页面 代理用户列表
     *
     * @return org.springframework.web.servlet.ModelAndView
     * @author leehao
     */
    @GetMapping(value = AgentMapping.SHOW_AGENT_LIST)
    public ModelAndView showAgentList() {
        List<AgentLevelEnums> agentList = AgentLevelEnums.queryList();
        ModelAndView view = new ModelAndView(AgentMapping.SHOW_AGENT_LIST);
        view.addObject("agentList", agentList);
        return view;
    }

    /**
     * 数据接口 代理用户列表
     *
     * @param page  分页
     * @param agent 查询
     * @return com.sxbbc.common.basics.rest.RestResponse
     * @author leehao
     */
    @RequestMapping(value = AgentMapping.QUERY_AGENT_LIST)
    @ResponseBody
    public com.sxbbc.common.basics.rest.RestResponse queryAgentList(BasePage<AgAgent> page, AgAgent agent) {
        agAgentService.queryAgentList(page, agent);
        return RestFactory.success(page.getRecords(), page.getTotal());
    }

    /**
     * 页面 新增编辑代理页面
     *
     * @param id 代理ID
     * @return org.springframework.web.servlet.ModelAndView
     * @author leehao
     */
    @RequestMapping(value = AgentMapping.SHOW_EDIT_AGENT)
    public ModelAndView showEditAgent(Integer id) {
        AgAgent agent = agAgentService.getById(id);
        Address address = new Address();
        address.setPid(StaticUtils.ADDRESS_COUNTRY);
        List<Address> proList = addressService.queryAddressByParentId(address);
        List<Address> cityList = new ArrayList<>();
        List<Address> areaList = new ArrayList<>();
        if (agent != null && agent.getProId() != null) {
            address.setPid(agent.getProId());
            cityList = addressService.queryAddressByParentId(address);
        }
        if (agent != null && agent.getCityId() != null) {
            address.setPid(agent.getCityId());
            areaList = addressService.queryAddressByParentId(address);
        }
        List<AgentLevelEnums> agentList = AgentLevelEnums.queryList();
        ModelAndView view = new ModelAndView(AgentMapping.SHOW_EDIT_AGENT);
        view.addObject("agent", agent);
        view.addObject("proList", proList);
        view.addObject("cityList", cityList);
        view.addObject("areaList", areaList);
        view.addObject("agentList", agentList);
        return view;
    }

    /**
     * 操作 保存编辑代理
     *
     * @param agent 代理对象
     * @return com.function.common.RestResponse
     * @author leehao
     */
    @RequestMapping(value = AgentMapping.EDIT_AGENT)
    @ResponseBody
    @SystemLog(methods = "保存代理用户", module = "代理管理")
    public RestResponse editAgent(AgAgent agent) {
        return agAgentService.editAgent(agent);
    }

    /**
     * 变更代理状态
     *
     * @param agent
     * @return com.function.common.RestResponse
     * @author leehao
     */
    @RequestMapping(value = AgentMapping.HANDLE_UPDATE_STATUS)
    @ResponseBody
    @SystemLog(methods = "更改代理状态", module = "代理管理")
    public RestResponse handleUpdateStatus(AgAgent agent) {
        if (agent.getId() == null) {
            return GetRest.getFail("获取代理用户失败");
        }
        if (agent.getStatus() == null) {
            return GetRest.getFail("获取状态失败");
        }
        AgAgent agAgent = agAgentService.getById(agent.getId());
        if (agAgent == null) {
            return GetRest.getFail("该代理用户不存在");
        }

        CalcuUtils calcuUtils = CalcuUtils.getInstance();
        if (calcuUtils.isEquals(agent.getStatus(), StaticUtils.STATUS_SUCCESS)) {
            //判断是否已经有代理
            QueryWrapper<AgAgent> wrapper = new QueryWrapper<>();
            wrapper.eq("level", agAgent.getLevel()).eq("status", StaticUtils.STATUS_SUCCESS);
            if (calcuUtils.isEquals(agAgent.getLevel(), AgentLevelEnums.PROVINCE_AGENT.getId())) {
                wrapper.eq("pro_id", agAgent.getProId());
            } else if (calcuUtils.isEquals(agAgent.getLevel(), AgentLevelEnums.CITY_AGENT.getId())) {
                wrapper.eq("pro_id", agAgent.getProId());
                wrapper.eq("city_id", agAgent.getCityId());
            } else if (calcuUtils.isEquals(agAgent.getLevel(), AgentLevelEnums.AREA_AGENT.getId())) {
                wrapper.eq("pro_id", agAgent.getProId());
                wrapper.eq("city_id", agAgent.getCityId());
                wrapper.eq("area_id", agAgent.getAreaId());
            }
            int count = agAgentService.count(wrapper);
            if (count > 0) {
                return GetRest.getFail("该区域已存在代理，不可重复添加");
            }
        }

        agAgent.setStatus(agent.getStatus());
        agAgent.setRoleId(StaticUtils.AGENT_ROLE_1);
        boolean update = agAgentService.updateById(agAgent);
        if (!update) {
            throw new ThrowJsonException("更新代理用户状态失败");
        }
        QueryWrapper<AgAccount> wrapper = new QueryWrapper<>();
        wrapper.eq("agid", agent.getId());
        AgAccount account = iAgAccountService.getOne(wrapper);
        if (calcuUtils.isEquals(agent.getStatus(), StaticUtils.STATUS_SUCCESS) && account == null) {
            AgAccount agAccount = new AgAccount();
            agAccount.setCid(agAgent.getCid());
            agAccount.setAgid(agAgent.getId());
            update = iAgAccountService.save(agAccount);
            if (!update) {
                throw new ThrowJsonException("更新代理用户状态失败");
            }
        }
        return GetRest.getSuccess("操作成功");
    }

    /**
     * 删除代理
     *
     * @param id 代理ID
     * @return com.function.common.RestResponse
     * @author leehao
     */
    @RequestMapping(value = AgentMapping.DELETE_AGENT)
    @ResponseBody
    @SystemLog(methods = "删除代理用户", module = "代理管理")
    public RestResponse deleteAgent(Integer id) {
        AgAgent agent = agAgentService.getById(id);
        if (agent == null) {
            return GetRest.getFail("该代理不存在");
        }
        boolean delete = agAgentService.removeById(id);
        if (!delete) {
            throw new ThrowJsonException("删除代理用户失败");
        }
        return GetRest.getSuccess("删除成功");
    }

    /**
     * 代理收益明细页面
     *
     * @param donate
     * @return org.springframework.web.servlet.ModelAndView
     * @author leehao
     */
    @GetMapping(value = AgentMapping.SHOW_ACCOUNT_DETAIL)
    public ModelAndView showAccountDetail(AgDonateDetail donate) {
        List<HandleTypeEnums> handleList = HandleTypeEnums.queryList();
        ModelAndView view = new ModelAndView(AgentMapping.SHOW_ACCOUNT_DETAIL);
        view.addObject("handleList", handleList);
        view.addObject("detail", donate);
        return view;
    }

    /**
     * 查询代理资金明细列表
     *
     * @param vo 资金明细查询条件
     * @return
     * @author Wahyee
     */
    @RequestMapping(value = AgentMapping.QUERY_ACCOUNT_DETAIL)
    @ResponseBody
    public com.sxbbc.common.basics.rest.RestResponse queryAccountDetail(BasePage<T> page, AccountDetailVO vo) {
        String timestr = vo.getTimestr();
        if (null == vo.getAgid()) {
            return RestFactory.fail("代理信息获取失败，请刷新后重试");
        }
        if (vo.getFundType() == null) {
            vo.setFundType(FundTypeEnums.MONEY.getId());
        }
        if (StringUtils.isBlank(vo.getPayCode())) {
            vo.setPayCode(null);
        }

        CalcuUtils calc = CalcuUtils.getInstance();
        if (calc.isEquals(vo.getFundType(), FundTypeEnums.MONEY.getId())) {
            AgMoneyDetail entiy = new AgMoneyDetail();
            BeanUtils.copyProperties(vo, entiy);
            QueryWrapper<AgMoneyDetail> wrapper = new QueryWrapper<AgMoneyDetail>(entiy);

            wrapper.orderByDesc("create_time");
            if (!StringUtils.isBlank(timestr)) {
                String[] timeArr = timestr.split("~");
                if (!StringUtils.isBlank(timeArr[0]) && !StringUtils.isBlank(timeArr[1])) {
                    wrapper.between("create_time", timeArr[0], timeArr[1]);
                }
            }

            Page<AgMoneyDetail> page1 = new BasePage<AgMoneyDetail>();
            page1.setCurrent(page.getCurrent());
            iAgMoneyDetailService.page(page1, wrapper);
            for (AgMoneyDetail o : page1.getRecords()) {
                o.setTypeName(HandleTypeEnums.getName(o.getTypeId()));
            }
            return RestFactory.success(page1.getRecords(), page1.getTotal());
        } else if (calc.isEquals(vo.getFundType(), FundTypeEnums.DONATE.getId())) {
            AgDonateDetail entiy = new AgDonateDetail();
            BeanUtils.copyProperties(vo, entiy);
            QueryWrapper<AgDonateDetail> wrapper = new QueryWrapper<AgDonateDetail>(entiy);

            wrapper.orderByDesc("create_time");
            if (!StringUtils.isBlank(timestr)) {
                String[] timeArr = timestr.split("~");
                if (!StringUtils.isBlank(timeArr[0]) && !StringUtils.isBlank(timeArr[1])) {
                    wrapper.between("create_time", timeArr[0], timeArr[1]);
                }
            }

            Page<AgDonateDetail> page1 = new BasePage<AgDonateDetail>();
            page1.setCurrent(page.getCurrent());
            iAgDonateDetailService.page(page1, wrapper);
            for (AgDonateDetail o : page1.getRecords()) {
                o.setTypeName(HandleTypeEnums.getName(o.getTypeId()));
            }
            return RestFactory.success(page1.getRecords(), page1.getTotal());
        } else if (calc.isEquals(vo.getFundType(), FundTypeEnums.SHARE.getId())) {
            AgShareDetail entiy = new AgShareDetail();
            BeanUtils.copyProperties(vo, entiy);
            QueryWrapper<AgShareDetail> wrapper = new QueryWrapper<AgShareDetail>(entiy);

            wrapper.orderByDesc("create_time");
            if (!StringUtils.isBlank(timestr)) {
                String[] timeArr = timestr.split("~");
                if (!StringUtils.isBlank(timeArr[0]) && !StringUtils.isBlank(timeArr[1])) {
                    wrapper.between("create_time", timeArr[0], timeArr[1]);
                }
            }

            Page<AgShareDetail> page1 = new BasePage<AgShareDetail>();
            page1.setCurrent(page.getCurrent());
            iAgShareDetailService.page(page1, wrapper);
            for (AgShareDetail o : page1.getRecords()) {
                o.setTypeName(HandleTypeEnums.getName(o.getTypeId()));
            }
            return RestFactory.success(page1.getRecords(), page1.getTotal());
        }
        return RestFactory.success(page.getRecords(), page.getTotal());
    }

    /**
     * 赠送扣除代理贡献值页面
     *
     * @param isout 1赠送 0扣除
     * @param agid  代理ID
     * @return org.springframework.web.servlet.ModelAndView
     * @author leehao
     */
    @RequestMapping(value = AgentMapping.SHOW_ACCOUNT_DETAIL_EDIT)
    public ModelAndView showHandleDonate(Integer isout, Integer agid) {
        List<HandleTypeEnums> handleList = HandleTypeEnums.queryList();
        ModelAndView view = new ModelAndView(AgentMapping.SHOW_ACCOUNT_DETAIL_EDIT);
        view.addObject("isout", isout);
        view.addObject("agid", agid);
        view.addObject("handleList", handleList);
        view.addObject("fundType", FundTypeEnums.queryList());
        return view;
    }

    /**
     * 代理角色页面
     *
     * @return org.springframework.web.servlet.ModelAndView
     * @author leehao
     */
    @RequestMapping(value = AgentMapping.SHOW_AGENT_ROLE)
    public ModelAndView showAgentRole() {
        QueryWrapper<AgRoles> wrapper = new QueryWrapper<>();
        wrapper.eq("target_id", 0);
        List<AgRoles> list = agRolesService.list(wrapper);
        ModelAndView view = new ModelAndView(AgentMapping.SHOW_AGENT_ROLE);
        view.addObject("list", list);
        return view;
    }

    /**
     * 页面 编辑代理角色
     *
     * @return org.springframework.web.servlet.ModelAndView
     * @author leehao
     */
    @RequestMapping(value = AgentMapping.SHOW_EDIT_AGENT_ROLE)
    public ModelAndView showEditAgentRole() {
        QueryWrapper<AgRoles> wrapper = new QueryWrapper<>();
        wrapper.eq("target_id", 0);
        AgRoles role = agRolesService.getOne(wrapper);
        List<AgMenus> list = agRolesService.queryMenusByRoleId(role.getId());
        ModelAndView view = new ModelAndView(AgentMapping.SHOW_EDIT_AGENT_ROLE);
        view.addObject("role", role);
        view.addObject("list", list);
        return view;
    }

    /**
     * 操作 编辑代理角色
     *
     * @param role
     * @return com.function.common.RestResponse
     * @author leehao
     */
    @RequestMapping(value = AgentMapping.EDIT_AGENT_ROLE)
    @ResponseBody
    @SystemLog(methods = "保存编辑代理角色", module = "代理管理")
    public RestResponse editAgentRole(AgRoles role) {
        if (StringUtils.isBlank(role.getName())) {
            return GetRest.getFail("请填写角色名称");
        }
        if (StringUtils.isBlank(role.getMenuIds())) {
            return GetRest.getFail("请选择菜单");
        }
        Set<String> menuList = new HashSet<>(Arrays.asList(role.getMenuIds().split(",")));
        String menus = StringUtils.join(menuList.toArray(), ",");
        role.setMenuIds(menus);
        boolean save = agRolesService.saveOrUpdate(role);
        if (!save) {
            throw new ThrowJsonException("保存角色失败");
        }
        return GetRest.getSuccess("保存成功");
    }
}